<template>
  <div class="p-2">
    <transition>
      <div class="search" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="系统模块" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入系统模块"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="人员类别" prop="operatorType">
            <el-select
              v-model="queryParams.operatorType"
              clearable
              placeholder="Select"
            >
              <el-option
                v-for="item in operatorTypeArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="操作状态" prop="status">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="Select"
            >
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="提交时间" prop="age">
            <el-date-picker
              v-model="queryParams.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="handleDateRangeChange"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <!-- 按钮区 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['system:operationalLog:remove']"
            >
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Delete"
              :disabled="multiple"
              v-hasPermi="['system:operationalLog:export']"
            >
              导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Delete"
              :disabled="multiple"
              v-hasPermi="['system:user:export']"
            >
              导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="DeleteFilled"
              @click="handleCleanAll"
              v-hasPermi="['system:user:export']"
            >
              清空
            </el-button>
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getOperationalLogList"
          ></right-toolbar>
        </el-row>
      </template>

      <!-- 列表区 -->
      <el-table
        v-loading="loading"
        :data="operationalLogList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column
          label="日志编号"
          align="center"
          prop="id"
          v-if="true"
        />
        <el-table-column
          label="系统模块"
          align="center"
          prop="title"
          v-if="true"
        />
        <el-table-column label="请求方式" align="center" prop="requestMethod" />
        <el-table-column label="操作人员" align="center" prop="operatorName" />
        <el-table-column label="操作IP" align="center" prop="operationIp" />
        <el-table-column
          label="操作地点"
          align="center"
          prop="operationLocation"
        />

        <el-table-column label="操作状态" prop="status">
          <template #default="{ row }: { row: SysOperationalLogVo }">
            <el-tag
              :type="OperationalLogStyleTypeMap.get(row.status ?? -1) ?? 'info'"
              >{{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作日期" align="center" prop="operationTime" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              v-hasPermi="['system:operationalLog:query']"
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getOperationalLogList"
      />
    </el-card>

    <!-- 角色详情弹出框 -->
    <el-dialog
      v-model="dialogStatus.isVisible"
      :title="dialogStatus.title"
      width="55%"
      center
      append-to-body
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-descriptions class="margin-top" :column="3" size="large" border>
        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <el-icon>
                <user />
              </el-icon>
              操作者
            </div>
          </template>
          {{ currentDialogData.operatorName }}
        </el-descriptions-item>

        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <icon-ic-outline-view-module />
              操作模块
            </div>
          </template>
          {{ currentDialogData.title }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item" style="width: 120px">
              <el-icon>
                <location />
              </el-icon>
              操作位置
            </div>
          </template>
          {{ currentDialogData.operationLocation }}
          {{ currentDialogData.operationIp }}
        </el-descriptions-item>

        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <el-icon>
                <tickets />
              </el-icon>
              请求方式
            </div>
          </template>
          <el-tag size="small">{{ currentDialogData.requestMethod }}</el-tag>
        </el-descriptions-item>

        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <icon-ic-baseline-av-timer />
              请求耗时
            </div>
          </template>
          <el-tag size="small">{{ currentDialogData.costTime }}ms</el-tag>
        </el-descriptions-item>

        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <icon-ic-baseline-access-time />
              操作时间
            </div>
          </template>
          {{ currentDialogData.operationTime }}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="margin-top" :column="3" size="large" border>
        <el-descriptions-item width="135px">
          <template #label>
            <div class="cell-item">
              <icon-ic-outline-my-location />
              请求路径
            </div>
          </template>
          {{ currentDialogData.operationUrl }}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="margin-top" :column="3" size="large" border>
        <el-descriptions-item width="135px">
          <template #label>
            <div class="cell-item">
              <icon-ic-baseline-data-object />
              请求参数
            </div>
          </template>
          {{ currentDialogData.operationParam }}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions v-show="currentDialogData.errorMsg" class="margin-top" :column="3" size="large" border>
        <el-descriptions-item width="135px">
          <template #label>
            <div class="cell-item">
              <icon-ic-baseline-data-object />
              错误信息
            </div>
          </template>
          {{ currentDialogData.errorMsg }}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="margin-top" :column="3" size="large" border>
        <el-descriptions-item width="135px">
          <template #label>
            <div class="cell-item">
              <icon-ic-baseline-data-object />
              返回结果
            </div>
          </template>
          {{ currentDialogData.jsonResult }}
        </el-descriptions-item>
      </el-descriptions>

      <el-button
        plain
        size="large"
        style="margin: 20px 10px 10px 700px"
        @click="handleCloseDialog"
      >
        返回
      </el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getOperationalLogList as getOperationalLogListApi,
  getOperationalLogDetail as getOperationalLogDetailApi,
  deleteOperationalLog as deleteOperationalLogApi,
  cleanOperationalLog as cleanOperationalLogApi,
} from "@/service/api/system/operation";
import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import { User, Location, Tickets } from "@element-plus/icons-vue";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import { to } from "await-to-js";
import { SysOperationalLogVo } from "@/service/api/system/operation/types.ts";
import {
  OperationalLogStatusMap,
  OperationalLogStyleTypeMap,
} from "@/maps/system/operationalLog/operationalLogStatusMap.ts";
import { convertTimeRange } from "@/utils/request.ts";


// 列表数据
const operationalLogList = ref<SysOperationalLogVo[]>([]);

const loading = ref(true);
const ids = ref<Array<string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref(ElForm);
const showSearch = ref(true);

// 初始dialog状态
const initDialogStatus = {
  isVisible: false,
  title: "",
};

// 状态
const statusArr = reactive([
  {
    value: 0,
    label: "成功",
  },
  {
    value: 1,
    label: "失败",
  },
]);

const operatorTypeArr = reactive([
  {
    value: 0,
    label: "其他",
  },
  {
    value: 1,
    label: "后台用户",
  },
  {
    value: 2,
    label: "app端用户",
  },
]);

// 初始角色详情dialogData数据
const initDialogData: SysOperationalLogVo = {
  businessType: 5,
  costTime: 0,
  errorMsg: "",
  id: "",
  jsonResult: undefined,
  method: "",
  operationIp: "",
  operationLocation: "",
  operationParam: "",
  operationTime: undefined,
  operationUrl: "",
  operatorName: "",
  operatorType: 1,
  requestMethod: "",
  status: 0,
  title: "",
};

// 初始query参数
const initQueryParams = {
  title: "",
  operatorType: 1,
  status: 0,
  pageNum: 1,
  pageSize: 10,
  orderByColumn: "operationTime",
  orderType: "desc",
  timeRange:'',
  params: {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  },
};

// 搜索框数据
const data = reactive({
  queryParams: { ...initQueryParams },
  rules: {
    id: [{ required: true, message: "主键不能为空", trigger: "blur" }],
    name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
    email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
  },
  dialogStatus: { ...initDialogStatus },
  currentDialogData: {
    ...initDialogData,
  },
});
const { queryParams, currentDialogData, dialogStatus } = toRefs(data);

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  // console.log(queryParams.value)
  queryParams.value.pageNum = 1;
  getOperationalLogList();
};

/**
 * 将选择的开始结束日期转换为后端需要的形式
 * @param value
 */
 const handleDateRangeChange = (value: [Date | null, Date | null]) => {
  console.log(value);
  queryParams.value.params = convertTimeRange(value);
};


/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.value.timeRange = "";
  queryParams.value.params = {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  };
  handleQuery();
};

/**
 * 查询测试单列表
 */
const getOperationalLogList = async (): Promise<boolean> => {
  loading.value = true;
  console.log(queryParams.value);
  const [err, res] = await to<BasePageResponse<SysOperationalLogVo>, any>(
    getOperationalLogListApi(queryParams.value),
  );
  console.log("!!!", res);
  if (!err) {
    operationalLogList.value = res?.rows ?? [];
    total.value = Number(res?.total ?? 0);
    operationalLogList.value.forEach((item: SysOperationalLogVo) => {
      item.statusMsg = OperationalLogStatusMap.get(item.status ?? -1) ?? "未知";
    });

    loading.value = false;
    return true;
  }
  loading.value = false;
  return false;
};

/**
 * 多选框选中数据
 */
const handleSelectionChange = (selection: SysOperationalLogVo[]) => {
  ids.value = selection.map((item) => item.id ?? "").filter((id) => id !== "");
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(ids.value);
};

/**
 * 查看详情按钮
 */
const handleDetail = async (row: any) => {
  dialogStatus.value.title = "操作日志详情";
  dialogStatus.value.isVisible = true;
  console.log(row.id);
  const [err, res] = await to<BaseResponse<SysOperationalLogVo>, any>(
    getOperationalLogDetailApi(row.id),
  );

  if (!err) {
    currentDialogData.value = res?.data ?? initDialogData;
    console.log(data);
  }
};

/**
 * 关闭dialog
 */
const handleCloseDialog = () => {
  dialogStatus.value = Object.assign({}, initDialogStatus);
};

/**
 * 删除按钮操作
 */
const handleDelete = async () => {
  // 询问用户是否确认删除
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("此操作将永久删除选中的操作日志, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      message: "取消删除",
      type: "info",
    });
  } else if (confirm === "confirm") {
    const [err] = await to<BaseResponse<any>, any>(
      deleteOperationalLogApi(ids.value),
    );

    if (!err) {
      ElMessage({
        message: "删除操作日志成功",
        type: "success",
      });
      await getOperationalLogList();
    }
  }
};

/**
 * 清空所有日志
 */
const handleCleanAll = async () => {
  // 询问用户是否确认删除
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("此操作将永久清空所有操作日志, 是否继续?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      message: "取消清空",
      type: "info",
    });
  } else if (confirm === "confirm") {
    const [err] = await to<BaseResponse<any>, any>(
      cleanOperationalLogApi(ids.value),
    );

    if (!err) {
      ElMessage({
        message: "清空操作日志成功",
        type: "success",
      });
      await getOperationalLogList();
    }
  }
};

onMounted(() => {
  getOperationalLogList();
});
</script>

<style scoped lang="scss">
.el-date-pickerv {
  width: 900px;
}

.dialogForm {
  padding: 0 0 0 45px;

  // background-color: pink;
  .el-input {
    width: 219px;
  }
}

.dialogFooter {
  margin: 55px 0 0 220px;
}

.innerDialogFooter {
  margin: 55px 0 0 230px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .setting {
    margin-left: 30px;
  }
}

.innerFooter {
  margin: 20px 0 0 200px;
}
</style>
